package com.example.boot.dao;

import java.util.UUID;

import org.springframework.data.redis.core.ReactiveRedisOperations;
import org.springframework.stereotype.Component;

import com.example.boot.entity.User;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * 
 * @author KL 
 * @date  2018年3月2日
 * @description 直接操作redis数据的类，相当于dao层
 *
 */
@Component
public class UserRepository {

	//redis operations抽象接口
	ReactiveRedisOperations<String, User> template;

    public UserRepository(ReactiveRedisOperations<String, User> template) {
        this.template = template;
    }
    /**
     * 
     * @author KL
     * @date 2018年3月2日
     * @description: 获取reids中
     * @return Flux<User>
     */
    public Flux<User> findAll() {
        return template.<String, User>opsForHash().values("users");
    }

    public Mono<User> findById(String id) {
        return template.<String, User>opsForHash().get("users", id);
    }

    public Mono<User> save(User post) {
        if (post.getId() != null) {
            String id = UUID.randomUUID().toString();
            post.setId(id);
        }
        return template.<String, User>opsForHash().put("users", post.getId(), post)
            .log()
            .map(p -> post);

    }

    public Mono<Void> deleteById(String id) {
        return template.<String, User>opsForHash().remove("users", id)
            .flatMap(p -> Mono.<Void>empty());
    }

    public Mono<Boolean> deleteAll() {
        return template.<String, User>opsForHash().delete("users");
    }
}
